package net.betou.trade.main.dao.impl;

import net.betou.common.hibernate3.Finder;
import net.betou.common.hibernate3.HibernateBaseDao;
import net.betou.common.page.Pagination;
import net.betou.trade.entity.main.Suggestion;
import net.betou.trade.main.dao.SuggestionDao;

import org.springframework.stereotype.Repository;

@Repository
public class SuggestionDaoImpl extends HibernateBaseDao< Suggestion, Integer > implements SuggestionDao{

	@Override
	protected Class< Suggestion > getEntityClass( ) {
		return Suggestion.class;
	}

	public Suggestion deleteById( Integer id ) {
		Suggestion bean = get( id );
		if( bean != null ){
			getSession( ).delete( bean );
		}
		
		return bean;
	}

	public Suggestion findById( Integer id ) {
		return get(id);
	}

	public Suggestion save( Suggestion bean ) {
		getSession( ).save( bean );
		return bean;
	}
	
	@SuppressWarnings("unchecked")
	public Pagination getPage(Integer selfId, String topIntermedia, String deepHql, String searchProperty, String searchValue, String orderProperty, String orderDirection, int pageNo, int pageSize, String filter){
		
		Finder f = Finder.create( " from Suggestion bean where ( 1=1 " );
		
		if(deepHql!=null && deepHql.length()>0){
			f.append(" and ");
			f.append(deepHql);
			f.append(" or 1=1 ");
		}
		
		if(selfId != null || topIntermedia!=null && topIntermedia.length()>0){
			f.append(" and(");
			if( selfId != null ){
				f.append( " bean.admin.id=:id" );
				f.setParam( "id", selfId );
			}
			if(selfId != null && topIntermedia!=null && topIntermedia.length()>0){
				f.append(" or ");
			}
			if(topIntermedia!=null && topIntermedia.length()>0){
				f.append(" bean.admin in( select a from AgentAndAdmins a where a.topIntermedia||',' like :topIntermedia||',%' ) ");
				f.setParam("topIntermedia", topIntermedia);
			}
			f.append(")");
		}
		f.append(" )");
		if(filter!=null){
			createFilter( f, filter );
		}
		createSearch( f, searchProperty, searchValue );
		createOrder( f, orderProperty, orderDirection, "id" );
		log.info(f.getRowCountHql());
		return find( f, pageNo, pageSize );
		
	}
	
	public Suggestion findMySuggestion( Integer id, Integer selfId ){
		String hql = "from Suggestion bean where bean.id=? and bean.admin.id=?";
		return ( Suggestion ) this.findUnique( hql, id, selfId );
	}
}